package org.nbile.component;

import org.stellar.sdk.AssetTypeNative;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.Memo;
import org.stellar.sdk.PaymentOperation;
import org.stellar.sdk.Server;
import org.stellar.sdk.Transaction;
import org.stellar.sdk.responses.AccountResponse;
import org.stellar.sdk.responses.SubmitTransactionResponse;

/**
 * Document Start 
 * 通道组件
 * Document End 
 * Author: songwenpeng@le.com
 * Time: 2016年11月7日 下午2:12:44
 */
public class ChannelComponent {

	/**
	 * Document Start 
	 * 向指定账户Payment XLM
	 * 异常返回Null
	 * Document End 
	 * Author: songwenpeng@le.com
	 * Time: 2016年10月3日 下午1:00:40
	 * @param sourceSeed
	 * @param targetAccountID
	 * @param amount
	 * @return
	 */
	public SubmitTransactionResponse paymentXLM(Server server, String sourceSeed, String targetAccountID, String amount) {
		//创建源 目标 账户对象
		KeyPair source = KeyPair.fromSecretSeed(sourceSeed);
		KeyPair destination = KeyPair.fromAccountId(targetAccountID);
		try {
			// First, check to make sure that the destination account exists.
			// You could skip this, but if the account does not exist, you will be charged
			// the transaction fee when the transaction fails.
			// It will throw HttpResponseException if account does not exist or there was another error.
			server.accounts().account(destination);

			// If there was no error, load up-to-date information on your account.
			AccountResponse sourceAccount = server.accounts().account(source);

			// Start building the transaction.
			Transaction transaction = new Transaction.Builder(sourceAccount).addOperation(new PaymentOperation.Builder(destination, new AssetTypeNative(), amount).build())
					// A memo allows you to add your own metadata to a transaction. It's
					// optional and does not affect how Stellar treats the transaction.
					.addMemo(Memo.text("Tranfer XLM")).build();
			// Sign the transaction to prove you are actually the person sending it.
			transaction.sign(source);
			// And finally, send it off to Stellar!
			SubmitTransactionResponse response = server.submitTransaction(transaction);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
